<?php

/**
 * Class Users
 *
 * Klasa odpowiedzialna za zdarzenia zwiazane z obsluga uzytkownikow
 *
 * @author Jakub Budzisz
 * @since 15.08.2007
 * @version 0.7
 * @name Users
 */
class Users extends Bsystem {

	function __construct() {
		parent::__construct();
	}

	/**
	 * Checks if user is logged ($_SESSION['logged'] set)
	 *
	 * @return bool
	 */
	public function CheckIfLogged() {
		if (isset($_SESSION['logged']))
			return true;
		else
			return false;
	}

	/**
	 * Checks if the login try has been sucessfull
	 *
	 * @param str $username
	 * @param str $password
	 * @return bool
	 */
	public function LoginTry($username, $password) {
		if (!isset($_SESSION['logged'])) {
			$username = trim(DB::SecureUserInput($username));
			$password = trim(DB::SecureUserInput($password));
			if ($this->password_hashing == true)
				$password = md5($password);

			$db = new Db();
			$result = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "users WHERE username = '$username' AND deleted = 0");

//			echo "<pre>",print_r($result),"</pre>";exit;

			if ($result == true) {
				if ($result['password'] == $password) {
					if ($this->ActivateUser($result['user_id']))  // all data is correct, activating user
						return true;
					else
						return false;
				}
				else // bad password
					return false;
			}
			else {   // other error with connection
				return false;
			}
		}  // already logged in
		else
			return true;
	}

	/**
	 * Activates user with given id, sets new cookie and generates new session id.
	 *
	 * @param int $id
	 * @return bool
	 */
	public function ActivateUser($id) {
		$_SESSION['logged'] = 1;
		$_SESSION['user_id'] = $id;
		$_SESSION['username'] = $result['zdrobnienie'];
		$_SESSION['fullname'] = $result['imie'] . ' ' . $result['nazwisko'];
		$_SESSION['user'] = $result;



		// updating session_id in cookie
		if (isset($_POST['save_login'])) {
			$session_id = session_id();

			setcookie($this->cookie_name, $session_id, time() + (60 * 60 * 24 * 1));

			DB::DoInsert("UPDATE ".DB_PREFIX."users SET last_session_id = '" . $session_id . "',
								 			last_activity = NOW() WHERE user_id = $id");
		} else {
			DB::DoInsert("UPDATE ".DB_PREFIX."users SET last_activity = NOW() WHERE user_id = $id");
		}

		//$this->DodajLogowanie($id);

		return true;
	}

	/**
	 * Dodaj rekord z informacja o logowaniu uzytkownika do historii logowan
	 *
	 * @param int $id
	 * @return bool
	 */
	public function DodajLogowanie($id) {
		$cols[] = "user_id";
		$cols[] = "data";
		$cols[] = "ip";
		$vals[] = $id;
		$vals[] = "NOW()";
		$vals[] = $_SERVER['REMOTE_ADDR'];

		return $this->DoInsert('tbl_logons', $cols, $vals);
	}

}

?>
